var localStream = null,
	stompClient = null,
	//远程客户端
	pc = new Map();

var pcConfig = {
    'iceServers':[{
		'url':'stun:stun.l.google.com:19302'
	}]
}

//公共信息处理
function handleCommonMessage(message){
	// vm.notice.push(message.body);
}

//私人信息处理
function handlePrivateMessage(message){
	var payload = JSON.parse(message.body);
	console.log("handlePrivateMessage command",payload.command);
	switch(payload.command){
	case 'talk-msg':
		// console.log(payload);
		WebRTC.msghandler(payload);
		break;
	case 'msg':
		WebRTC.msghandler(payload);
		break;
	case 'wait':
		alert("当前房间没有人，请稍后")
		break;
	case 'preparePeerConnection':
		//接收方 准备peerConnection
		createPeerConnection(payload.sender);
		break;
	case 'ready':
		//收到ready发送SDP
		fireSDP(payload.sender);
		break;
	case 'client-fire-join':
		var temp = [];
		temp.push(payload.sender);
		joinRoom(temp);
		break;
	case 'join':
		// getSelfVideo();
		//TODO  生成方准备peercpeerConnection
		joinRoom(payload.data);
		break;
	case 'full':
		alert("房间已满");
		break;
	case 'end':
		closeWebRTC();
		break;
	case 'offer':
		// getSelfVideo();
		var sdp = JSON.parse(payload.data);
		// reactOffer(payload.sender,sdp);
		receiveSDP(payload.sender,sdp);
		break;
	case 'answer':
		var sdp = JSON.parse(payload.data);
		pc.get(payload.sender).setRemoteDescription(new RTCSessionDescription(sdp));
		break;
	case 'candidate':
		var candidate = new RTCIceCandidate(JSON.parse(payload.data));
		pc.get(payload.sender).addIceCandidate(candidate).then(function(e){
			console.log("成功添加ice candidate",e);
		}).catch(function(e){
			console.log(e);
		});
		break;
	default:
		console.log("default");
		break;
	}
}

//获取摄像头和麦克风，供远程使用
function getSelfVideo(){
	navigator.mediaDevices.getUserMedia({
		video:true
	}).then(
		function(stream){
			WebRTC.localVideo = window.URL.createObjectURL(stream);
		},function(err){
			// console.debug("获取媒体资源时出错err",err);
	}).catch(function(e){
		// console.debug("获取媒体资源时出错e",e);
	});
}

//获取摄像头和麦克风，供远程使用
function getUM(){
	return new Promise(function(resolve, reject){
		navigator.mediaDevices.getUserMedia({
			video:true,
			audio:true
		}).then(
			function(stream){
				localStream = stream;
				resolve();
			},function(err){
				// console.debug("获取媒体资源时出错err",err);
				reject(err);
		}).catch(function(e){
			// console.debug("获取媒体资源时出错e",e);
			reject(e);
		});
	});
}

function joinRoom(target){
	if(localStream != null){
		for(var i = 0;i<target.length;i++){
			createPeerConnectionBySender(target[i]);
		}
	}else{
		getUM().then(function(){
			for(var i = 0;i<target.length;i++){
				createPeerConnectionBySender(target[i]);
			}
		});
	}
}

function createPeerConnectionBySender(target){
		var peerConnection = new RTCPeerConnection(pcConfig);
		peerConnection.targetUser = target;
		peerConnection.onicecandidate = function(event){
				if(event.candidate){
					stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"candidate","target":this.targetUser,"data":JSON.stringify(event.candidate)}));
				}else{
					// console.debug("End of candidates.");
				}
		}
		peerConnection.onicecandidatestatechange = onIceStateChange;
		peerConnection.onaddstream = handleRemoteStreamAdded;
		peerConnection.onremovestream = handleRemoteStreamRemoved;
//		peerConnection.ondatachannel = receivehandler;
		peerConnection.addStream(localStream);

		pc.set(target,peerConnection);
		stompClient.send(transferChannel,{},JSON.stringify({"command":"preparePeerConnection","target":target}));
}

function reactOffer(target){
	console.log("reactOffer");
	if(localStream != null){
		createAnswer(target,sdp);
	}else{
		getUM().then(function(){
			createAnswer(target,sdp);
		});
	}
}


function createPeerConnection(target){
	console.log("createPeerConnectionByReceiver 01");
	if(localStream != null){
		console.log("createPeerConnectionByReceiver 02");
		createPeerConnectionByReceiver(target);
	}else{
		console.log("createPeerConnectionByReceiver 03");
		getUM().then(function(){
			createPeerConnectionByReceiver(target);
		},function(e){
			console.log("媒体资源获取出错e",e);
		}).catch(function(err){
			console.log("媒体资源获取出错err",e);
		});
	}
	console.log("createPeerConnectionByReceiver 04");
}

function createPeerConnectionByReceiver(target){
	console.log("createPeerConnectionByReceiver 被处罚");
	var peerConnection = new RTCPeerConnection(pcConfig);
	peerConnection.targetUser = target;
	peerConnection.onicecandidate = function(event){
			if(event.candidate){
				stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"candidate","target":this.targetUser,"data":JSON.stringify(event.candidate)}));
			}else{
				// console.debug("End of candidates.");
			}
	}
	peerConnection.onicecandidatestatechange = onIceStateChange;
	peerConnection.onaddstream = handleRemoteStreamAdded;
	peerConnection.onremovestream = handleRemoteStreamRemoved;
//	peerConnection.ondatachannel = receivehandler;
	
	peerConnection.addStream(localStream);
	pc.set(target,peerConnection);
	stompClient.send(transferChannel,{},JSON.stringify({"command":"ready","target":target}));	
}

function fireSDP(target){
	var peerConnection = pc.get(target);
	peerConnection.createOffer(function(sdp){
			peerConnection.setLocalDescription(sdp);
			stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"offer","target":target,"data":JSON.stringify(sdp)}));
		}, handleCreateOfferError);
}

function receiveSDP(target,sdp){
	var peerConnection = pc.get(target);
	peerConnection.setRemoteDescription(new RTCSessionDescription(sdp));
	peerConnection.createAnswer().then(function(sdp){
		peerConnection.setLocalDescription(sdp);
		stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"answer","target":target,"data":JSON.stringify(sdp)}));
	},onCreateSessionDescriptionError);
}

function createAnswer(target,sdp){
	console.log("创建Answer")
	var peerConnection = new RTCPeerConnection(pcConfig);
	pc.set(target,peerConnection);
	peerConnection.targetUser = target;
	peerConnection.onicecandidate = function(event){
			if(event.candidate){
				stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"candidate","target":this.targetUser,"data":JSON.stringify(event.candidate)}));
			}else{
				// console.debug("End of candidates.");
			}
	}
	peerConnection.onicecandidatestatechange = onIceStateChange;
	peerConnection.onaddstream = handleRemoteStreamAdded;
	peerConnection.onremovestream = handleRemoteStreamRemoved;
//	peerConnection.ondatachannel = receivehandler;
	
	peerConnection.addStream(localStream);
	peerConnection.createAnswer().then(function(sdp){
		peerConnection.setLocalDescription(sdp);
		stompClient.send(transferChannel,{},JSON.stringify({"dest":WebRTC.currentDest,"command":"answer","target":target,"data":JSON.stringify(sdp)}));
	},onCreateSessionDescriptionError);
	
	peerConnection.setRemoteDescription(new RTCSessionDescription(sdp));
}

function onIceStateChange(event){
	// console.debug("Ice State has change: "+e);
}

function handleRemoteStreamAdded(event){
	console.debug("发生添加媒体流事件",event);
	WebRTC.remoteStream.push(window.URL.createObjectURL(event.stream));
}

function handleRemoteStreamRemoved(event) {
	//   console.debug('Remote stream removed. Event: ', event);
}

function handleCreateOfferError(event){
	// console.debug("createOffer() error: ",event);
}

function onCreateSessionDescriptionError(error) {
	//   console.debug('Failed to create session description: ' + error.toString());
}

/**
 * 需要供外部使用
 * 1. 服务器链接状态
 * 2. 视频通话时，自己的图像
 * 3. 文字通讯时，文字的输出和输入
 */

//WebRTC对象
var WebRTC = {
    //服务器连接状态标识
    connflag:false,
	//本地视频流,给自己看自己用
	localVideo:null,
	//对方（远程）提供音频/视频流
	remoteStream:[],
	//当前所在频道
	currentDest:null,
	//stomp客户端
    stomp:null,
	//文本信息输出
	textOutput:null,
	//信息处理
	msghandler:null,

    //初始化网络
    init: function(){
        let stomp = Stomp.over(new SockJS(endPoint));
        stomp.connect({},function(frame){
            //订阅公共信息源
            stomp.subscribe(commonChannel,handleCommonMessage);
            //订阅个人信息源
            stomp.subscribe(privateChannel,handlePrivateMessage);
			WebRTC.stomp = stomp;
			WebRTC.connflag = stomp.connected;
			stompClient = WebRTC.stomp;
        },function(err){
			// WebRTC.connflag = false;
			WebRTC.connflag = stomp.connected;
			// alert("打开网络失败");
        });
    },

	reinit: function(){
		WebRTC.stomp.disconnect(function(){
			WebRTC.init();
		});
	},

    //获取摄像头供自己使用，所以不需要获取麦克风，也不需要发送至远程
    getVideo: function(){
        return new Promise(function(resolve, reject){
            navigator.mediaDevices.getUserMedia({
                video:true
            }).then(
                function(stream){
                    resolve(stream);
                },function(err){
                    // console.debug("获取媒体资源时出错err",err)
            }).catch(function(e){
                // console.debug("获取媒体资源时出错e",e);
            });
        });
    },

    //加入房间
    joinTargetRoom: function(type,targetRoom){
		let stomp = WebRTC.stomp;
        if(WebRTC.connflag){
            //订阅房间
			var roomSubscribe = null
			WebRTC.currentDest = "/topic/"+type+"-"+targetRoom;
			console.log(WebRTC.currentDest);
			// roomSubscribe = stomp.subscribe("/user"+WebRTC.currentDest,handlePrivateMessage);
			roomSubscribe = stomp.subscribe("/user"+WebRTC.currentDest,function(e){
				console.log("success");
			},function(e){
				console.log("err",e);
			});
            //发送加入房间指令
			return roomSubscribe;
        }else{
			alert("网络未连接");
		}
    },

	//发送信息
	sendMsg:function(target,msg){
		stompClient.send(transferChannel,{},JSON.stringify({"command":"msg","target":target,"data":msg}));
	},

	//设置外部信息处理句柄
	setMsgHandler(obj){
		WebRTC.msghandler = obj.msghandler;
	},

	sendTalkMsg:function(target,msg,dest){
		//dest == contactcode
		stompClient.send(talkChannel,{},JSON.stringify({"command":"talk-msg","dest":dest,"target":target,"data":msg}));
	}
}

export {WebRTC};
